<template>
  <div class="page-container">
    <VerticalTabNav />
    
    <div class="list-page">
      <!-- 搜索和操作区域 -->
      <div class="filter-area">
        <div class="search-area">
          <el-input
            v-model="searchValue"
            placeholder="请输入车牌号搜索"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="operation-area">
          <el-button 
            class="custom-button primary-button"
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>新增车辆
          </el-button>
          <el-button 
            class="custom-button success-button"
            @click="router.push('/basic-data/two-pages/car')"
          >
            <el-icon><Van /></el-icon>运输品信息
          </el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        height="calc(100vh - 250px)" 
        :header-cell-style="{ background: 'var(--el-bg-color-page)' }"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="车牌号" prop="licensePlate" min-width="120" />
        <el-table-column label="所有人" prop="owner" width="120" align="center" />
        <el-table-column label="所有人联系方式" prop="ownerContact" width="140" align="center" />
        <el-table-column label="驾驶证号" prop="driverLicense" width="160" align="center" />
        <el-table-column label="危化品运输许可证号" prop="hazardousPermit" min-width="180" align="center" />
        <el-table-column label="许可证有效期" prop="permitExpiry" width="120" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.permitExpiry) }}
          </template>
        </el-table-column>
        <el-table-column label="车辆类型" prop="vehicleType" width="120" align="center" />
        <el-table-column label="车辆品牌" prop="vehicleBrand" width="120" align="center" />
        <el-table-column label="车辆型号" prop="vehicleModel" width="120" align="center" />
        <el-table-column label="车辆颜色" prop="vehicleColor" width="100" align="center" />
        <el-table-column label="车辆长度(米)" prop="vehicleLength" width="120" align="center" />
        <el-table-column label="车辆宽度(米)" prop="vehicleWidth" width="120" align="center" />
        <el-table-column label="车辆高度(米)" prop="vehicleHeight" width="120" align="center" />
        <el-table-column label="车辆重量(吨)" prop="vehicleWeight" width="120" align="center" />
        <el-table-column label="载重(吨)" prop="loadCapacity" width="120" align="center" />
        <el-table-column label="车辆保险信息" prop="insuranceInfo" min-width="160" align="center" />
        <el-table-column label="保险有效期" prop="insuranceExpiry" width="120" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.insuranceExpiry) }}
          </template>
        </el-table-column>
        <el-table-column label="车辆年检信息" prop="inspectionInfo" min-width="160" align="center" />
        <el-table-column label="年检有效期" prop="inspectionExpiry" width="120" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.inspectionExpiry) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks" min-width="120" align="center">
          <template #default="scope">
            <span
              v-if="scope.row.remarks"
              class="remarks-text"
              @click="showRemarks(scope.row)"
            >{{ scope.row.remarks.length > 20 ? scope.row.remarks.slice(0, 20) + '...' : scope.row.remarks }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="success" link @click="handleTransport(scope.row)">运输信息</el-button>
            <el-button type="info" link @click="handleLocation(scope.row)">定位</el-button>
            <el-button type="warning" link @click="handleRoute(scope.row)">运输路线</el-button>
            <el-button type="danger" link @click="handleWarning(scope.row)">预警</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 15, 20, 25]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑/新增弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增危化品车辆' : '编辑危化品车辆'"
        width="60%"
        top="5vh"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="140px"
          class="dialog-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车牌号" prop="licensePlate">
                <el-input v-model="form.licensePlate" placeholder="请输入车牌号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所有人" prop="owner">
                <el-input v-model="form.owner" placeholder="请输入所有人姓名" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所有人联系方式" prop="ownerContact">
                <el-input v-model="form.ownerContact" placeholder="请输入联系方式" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="驾驶证号" prop="driverLicense">
                <el-input v-model="form.driverLicense" placeholder="请输入驾驶证号" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="危化品运输许可证号" prop="hazardousPermit">
                <el-input v-model="form.hazardousPermit" placeholder="请输入许可证号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="许可证有效期" prop="permitExpiry">
                <el-date-picker
                  v-model="form.permitExpiry"
                  type="datetime"
                  placeholder="选择有效期时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车辆类型" prop="vehicleType">
                <el-input v-model="form.vehicleType" placeholder="请输入车辆类型" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆品牌" prop="vehicleBrand">
                <el-input v-model="form.vehicleBrand" placeholder="请输入车辆品牌" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车辆型号" prop="vehicleModel">
                <el-input v-model="form.vehicleModel" placeholder="请输入车辆型号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆颜色" prop="vehicleColor">
                <el-input v-model="form.vehicleColor" placeholder="请输入车辆颜色" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="车辆长度(米)" prop="vehicleLength">
                <el-input-number 
                  v-model="form.vehicleLength" 
                  :precision="2" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆宽度(米)" prop="vehicleWidth">
                <el-input-number 
                  v-model="form.vehicleWidth" 
                  :precision="2" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆高度(米)" prop="vehicleHeight">
                <el-input-number 
                  v-model="form.vehicleHeight" 
                  :precision="2" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车辆重量(吨)" prop="vehicleWeight">
                <el-input-number 
                  v-model="form.vehicleWeight" 
                  :precision="2" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="载重(吨)" prop="loadCapacity">
                <el-input-number 
                  v-model="form.loadCapacity" 
                  :precision="2" 
                  :min="0" 
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车辆保险信息" prop="insuranceInfo">
                <el-input v-model="form.insuranceInfo" placeholder="请输入保险信息" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保险有效期" prop="insuranceExpiry">
                <el-date-picker
                  v-model="form.insuranceExpiry"
                  type="datetime"
                  placeholder="选择有效期时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车辆年检信息" prop="inspectionInfo">
                <el-input v-model="form.inspectionInfo" placeholder="请输入年检信息" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年检有效期" prop="inspectionExpiry">
                <el-date-picker
                  v-model="form.inspectionExpiry"
                  type="datetime"
                  placeholder="选择有效期时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="备注" prop="remarks">
            <el-input
              type="textarea"
              v-model="form.remarks"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 备注信息弹窗 -->
      <el-dialog
        v-model="remarksDialogVisible"
        title="备注信息"
        width="40%"
      >
        <div style="white-space: pre-wrap;">{{ currentRemarks }}</div>
        <template #footer>
          <span>
            <el-button @click="remarksDialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 预警弹窗 -->
      <el-dialog
        v-model="warningDialogVisible"
        title="车辆预警设置"
        width="50%"
      >
        <el-form
          ref="warningFormRef"
          :model="warningForm"
          label-width="120px"
        >
          <el-form-item label="预警类型" prop="warningType">
            <el-select v-model="warningForm.warningType" placeholder="请选择预警类型">
              <el-option label="超速预警" value="speed" />
              <el-option label="区域预警" value="area" />
              <el-option label="路线偏离" value="route" />
              <el-option label="疲劳驾驶" value="fatigue" />
            </el-select>
          </el-form-item>
          <el-form-item label="阈值" prop="threshold">
            <el-input-number 
              v-model="warningForm.threshold" 
              :min="0" 
              :precision="2"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="预警级别" prop="level">
            <el-select v-model="warningForm.level" placeholder="请选择预警级别">
              <el-option label="一般" value="normal" />
              <el-option label="重要" value="important" />
              <el-option label="紧急" value="urgent" />
            </el-select>
          </el-form-item>
          <el-form-item label="通知方式" prop="notifyType">
            <el-checkbox-group v-model="warningForm.notifyType">
              <el-checkbox label="短信" />
              <el-checkbox label="邮件" />
              <el-checkbox label="系统通知" />
              <el-checkbox label="电话" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              type="textarea"
              v-model="warningForm.remarks"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="warningDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitWarning">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Van } from '@element-plus/icons-vue'
import VerticalTabNav from '@/views/Bridge/basic-data/components/VerticalTabNav.vue'
import { 
  getDangerousGoodsCarInfo, 
  addDangerousGoodsCarInfo, 
  updateDangerousGoodsCarInfo, 
  deleteDangerousGoodsCarInfo, 
  getDangerousGoodsCarInfoById 
} from '@/api/bridge/bisc/car'
import dayjs from 'dayjs'

const router = useRouter()

// 表格数据相关
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchValue = ref('')
const selectedRows = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const remarksDialogVisible = ref(false)
const currentRemarks = ref('')

// 表单相关
const formRef = ref()
const form = ref({
  id: '',
  licensePlate: '',
  owner: '',
  ownerContact: '',
  driverLicense: '',
  hazardousPermit: '',
  permitExpiry: '',
  vehicleType: '',
  vehicleBrand: '',
  vehicleModel: '',
  vehicleColor: '',
  vehicleLength: 0,
  vehicleWidth: 0,
  vehicleHeight: 0,
  vehicleWeight: 0,
  loadCapacity: 0,
  insuranceInfo: '',
  insuranceExpiry: '',
  inspectionInfo: '',
  inspectionExpiry: '',
  remarks: ''
})

// 表单校验规则
const rules = {
  licensePlate: [{ required: true, message: '请输入车牌号', trigger: 'blur' }],
  owner: [{ required: true, message: '请输入所有人', trigger: 'blur' }],
  ownerContact: [{ required: true, message: '请输入所有人联系方式', trigger: 'blur' }],
  driverLicense: [{ required: true, message: '请输入驾驶证号', trigger: 'blur' }],
  hazardousPermit: [{ required: true, message: '请输入危化品运输许可证号', trigger: 'blur' }],
  permitExpiry: [{ required: true, message: '请选择许可证有效期', trigger: 'change' }],
  vehicleType: [{ required: true, message: '请输入车辆类型', trigger: 'blur' }],
}

// 预警弹窗相关
const warningDialogVisible = ref(false);
const warningFormRef = ref();
const warningForm = ref({
  warningType: '',
  threshold: 0,
  level: '',
  notifyType: [],
  remarks: ''
});

// 格式化日期
const formatDate = (date: string | number | Date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const params = {
      type: 0,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchValue.value
    }
    const res = await getDangerousGoodsCarInfo(params)
    tableData.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getList()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    id: '',
    licensePlate: '',
    owner: '',
    ownerContact: '',
    driverLicense: '',
    hazardousPermit: '',
    permitExpiry: '',
    vehicleType: '',
    vehicleBrand: '',
    vehicleModel: '',
    vehicleColor: '',
    vehicleLength: 0,
    vehicleWidth: 0,
    vehicleHeight: 0,
    vehicleWeight: 0,
    loadCapacity: 0,
    insuranceInfo: '',
    insuranceExpiry: '',
    inspectionInfo: '',
    inspectionExpiry: '',
    remarks: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: any) => {
  try {
    dialogType.value = 'edit'
    const res = await getDangerousGoodsCarInfoById(row.id)
    form.value = {
      ...res.data,
      permitExpiry: res.data.permitExpiry ? dayjs(res.data.permitExpiry).toDate() : null,
      insuranceExpiry: res.data.insuranceExpiry ? dayjs(res.data.insuranceExpiry).toDate() : null,
      inspectionExpiry: res.data.inspectionExpiry ? dayjs(res.data.inspectionExpiry).toDate() : null
    }
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该车辆信息吗？', '警告', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDangerousGoodsCarInfo(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const submitData = {
          ...form.value,
          type: 0,
          permitExpiry: form.value.permitExpiry ? dayjs(form.value.permitExpiry).format('YYYY-MM-DD HH:mm:ss') : null,
          insuranceExpiry: form.value.insuranceExpiry ? dayjs(form.value.insuranceExpiry).format('YYYY-MM-DD HH:mm:ss') : null,
          inspectionExpiry: form.value.inspectionExpiry ? dayjs(form.value.inspectionExpiry).format('YYYY-MM-DD HH:mm:ss') : null
        }

        if (form.value.id) {
          await updateDangerousGoodsCarInfo(submitData)
          ElMessage.success('修改成功')
        } else {
          await addDangerousGoodsCarInfo(submitData)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 显示备注信息
const showRemarks = (row: any) => {
  currentRemarks.value = row.remarks || '暂无备注'
  remarksDialogVisible.value = true
}

// 运输信息
const handleTransport = (row: any) => {
  router.push(`/basic-data/two-pages/car?vehicleId=${row.id}`);
};

// 定位
const handleLocation = (row: any) => {
  router.push(`/basic-data/three-pages/car-location?vehicleId=${row.id}`);
};

// 运输路线
const handleRoute = (row: any) => {
  router.push(`/basic-data/four-pages/car-route?vehicleId=${row.id}`);
};

// 预警
const handleWarning = (row: any) => {
  warningForm.value = {
    warningType: '',
    threshold: 0,
    level: '',
    notifyType: [],
    remarks: ''
  };
  warningDialogVisible.value = true;
};

// 提交预警设置
const submitWarning = async () => {
  if (!warningFormRef.value) return;
  await warningFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // TODO: 替换为实际的API调用
        ElMessage.success("预警设置成功");
        warningDialogVisible.value = false;
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

// 组件挂载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.list-page {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.filter-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .search-input {
    width: 300px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: var(--el-bg-color-overlay);
}

.el-dialog {
  border-radius: 12px;
  
  :deep(.el-dialog__body) {
    padding: 24px;
  }
  
  :deep(.el-dialog__header) {
    background: var(--el-bg-color-page);
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid var(--el-border-color-light);
  }
  
  :deep(.el-dialog__footer) {
    border-top: 1px solid var(--el-border-color-light);
    padding: 15px 20px;
  }
}

.dialog-form {
  :deep(.el-form-item__label) {
    color: var(--el-text-color-regular);
  }

  :deep(.el-input__inner) {
    background-color: var(--el-bg-color-overlay);
    border-color: var(--el-border-color);
    color: var(--el-text-color-primary);
  }
}

.operation-area {
  display: flex;
  gap: 12px;
  
  .custom-button {
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;
    
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      width: 0;
      height: 0;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      transform: translate(-50%, -50%);
      transition: width 0.6s ease, height 0.6s ease;
    }
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      
      &::before {
        width: 300px;
        height: 300px;
      }
    }
    
    &:active {
      transform: translateY(1px);
    }
  }

  .primary-button {
    background: var(--el-color-primary);
    border-color: var(--el-color-primary);
    color: white;
    
    &:hover {
      background: var(--el-color-primary-light-3);
      border-color: var(--el-color-primary-light-3);
    }
  }

  .success-button {
    background: #42b983;
    border-color: #42b983;
    color: white;
    
    &:hover {
      background: #4cd69b;
      border-color: #4cd69b;
    }
  }
}

.remarks-text {
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--el-color-primary);
  cursor: pointer;
  
  &:hover {
    text-decoration: underline;
  }
}
</style>

